package icu.lingjie.alone;

import icu.lingjie.util.ConfigUtil;
import icu.lingjie.util.MyUtil;
import lombok.Data;

import java.io.File;

/**
 * 器灵类
 */
@Data
public class QiLing {

    public static final String CODE_PREFIX = "Q";

    public QiLingState state;

    // 识海，记忆，堆，1M
    public int[] memory;

    // 灵台，意识，栈，32K
    public int[] conscious;

    public void init(int id) {
        // 初始化状态和 int 数组
        this.state = MyUtil.readJsonObjectFromFile(getJsonFileName(id), QiLingState.class);
        this.memory = MyUtil.readIntArrayFromFile(getMemoryFileName(id));
        this.conscious = MyUtil.readIntArrayFromFile(getConsciousFileName(id));
        if (this.state == null) {
            this.state = QiLingState.getNewInfo(id);
            this.memory = new int[this.state.memoryLength];
            this.conscious = new int[this.state.consciousLength];
            save();
        }
    }

    // 保存到磁盘
    public void save() {
        int id = this.state.id;
        MyUtil.writeJsonObjectFromFile(getJsonFileName(id), this.state);
        MyUtil.writeIntArrayToFile(getMemoryFileName(id), this.memory);
        MyUtil.writeIntArrayToFile(getConsciousFileName(id), this.conscious);
    }


    public static String getMemoryFileName(int id) {
        return ConfigUtil.器灵文件的目录 + File.separator + CODE_PREFIX + id + "_memory.ints";
    }
    public static String getConsciousFileName(int id) {
        return ConfigUtil.器灵文件的目录 + File.separator + CODE_PREFIX + id + "_conscious.ints";
    }
    public static String getJsonFileName(int id) {
        return ConfigUtil.器灵文件的目录 + File.separator + CODE_PREFIX + id + ".json";
    }

    // 器灵的状态
    @Data
    public static class QiLingState {
        // id
        public int id;

        // 编码，"Q"+id
        public String code;

        // 血条
        int healthPoint;
        int healthPointMax;

        // 灵力，蓝条
        int magicPoint;
        int magicPointMax;

        // 堆栈的长度
        int memoryLength;
        int consciousLength;
        // 栈的指针
        int consciousPoint;

        public static QiLingState getNewInfo(int id) {
            final QiLingState state = new QiLingState();
            state.id = id;
            state.code = CODE_PREFIX + id;
            state.healthPoint = 10_0000;
            state.healthPointMax = 20_0000;
            state.magicPoint = 10_0000;
            state.magicPointMax = 20_0000;
            state.memoryLength = 1<<18; // 1M
            state.consciousLength = 1<<14;
            state.consciousPoint = 0;
            return state;
        }
    }
}
